﻿using System;
using TraditionalMalteseCuisine.App_Code.Functions;
using TraditionalMalteseCuisine.App_Code.Objects;

namespace TraditionalMalteseCuisine
{
    public partial class NewRecipe : System.Web.UI.Page
    {
        #region Page Load
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                if (!((MainMasterPage)Master).IsLoggedIn)
                    Response.Redirect("default.aspx");
                else
                    BindControls();
            }
        }
        #endregion


        #region Events

        #endregion


        #region Buttons
        protected void btnSubmit_Click(object sender, EventArgs e)
        {
            if (cmbLevel.SelectedIndex > 0)
            {
                rfvLevel.IsValid = true;

                Recipe recipe = new Recipe();

                recipe.MemberID = ((MainMasterPage)Master).SiteMember.ID;
                recipe.LevelID = int.Parse(cmbLevel.SelectedValue);
                recipe.RecipeName = txtRecipeName.Text;
                recipe.Ingredients = txtIngredients.Text;
                recipe.Description = txtDescription.Text;
                recipe.Directions = txtDirections.Text;

                csvImageLocation.IsValid = ((uplImageLocation.FileName.Length == 0) || (Validation_Functions.IsValidImageFile(uplImageLocation.FileName)));

                if (uplImageLocation.FileName.Length > 0)
                {
                    string newImageFileName = string.Format("{0}{1}", Guid.NewGuid().ToString(), uplImageLocation.FileName.Substring(uplImageLocation.FileName.LastIndexOf('.')));
                    recipe.ImageLocation = string.Format("{0}{1}", Recipe.DEFAULT_IMAGE_FOLDER_LOCATION, newImageFileName);
                    recipe.ThumbnailLocation = string.Format("{0}{1}", Recipe.DEFAULT_THUMBNAIL_FOLDER_LOCATION, newImageFileName);
                }

                if ((csvImageLocation.IsValid) && (Site_Functions.AddRecipe(recipe)))
                {
                    if (uplImageLocation.FileName.Length > 0)
                    {
                        Site_Functions.SaveImageFile(uplImageLocation, Request.MapPath(recipe.ImageLocation), Request.MapPath(recipe.ThumbnailLocation), 100);
                    }

                    Response.Redirect(string.Format("details.aspx?item={0}", recipe.ID));
                }
            }
            else
            {
                rfvLevel.IsValid = false;
            }
        }
        #endregion


        #region Methods
        private void BindControls()
        {
            Web_Functions.LoadComboBox(Level.GetCommand_GetAllRecords(Level.TABLE_NAME), cmbLevel, Level.ID_TAG, Level.LEVEL_NAME_TAG);
        }
        #endregion
    }
}